<?php

namespace Home\Controller;
use My\Model\ProductOrderModel;
use Utuo\ForegroundController;
use Utuo\SystemInfo;

class ShopOrderController extends ForegroundController {
	
	// 购物车
	protected $cart = null;

	// 初始化
	public function _init() {
		layout ('shop');
		$this->setModelName ("PartnerProduct");
		$this->setModelControllerName("Shop");
		$this->checkLogin ();
		$this->cart = $this->getCart();
	}
	
	// 我的订单
	public function listAction() {
		$type = I ( "type" );
		$condition = array (
				"orders.uid" => $this->uid,
				"orders.pid" => $this->pid,
		);
		if ($type == 1) { // 未付款
			$condition ['orders.order_status'] = ProductOrderModel::ORDER_STATUS_PAY;
		} else if ($type == 2) { // 待签收(已付款,货到付款)
			$condition ['orders.order_status'] = array (
					"in",
					array (
							ProductOrderModel::ORDER_STATUS_SHIPPING,
							ProductOrderModel::ORDER_STATUS_SIGN
					)
			);
		} else if ($type == 3) { // 交易成功
			$condition ['orders.order_status'] = ProductOrderModel::ORDER_STATUS_COMPLETED;
		} else { // 其它
			$condition ['orders.order_status'] = array (
					"not in",
					array (
							ProductOrderModel::ORDER_STATUS_PAY,
							ProductOrderModel::ORDER_STATUS_SHIPPING,
							ProductOrderModel::ORDER_STATUS_SIGN,
							ProductOrderModel::ORDER_STATUS_COMPLETED,
					),
			);
		}
		$orderLists = M ( "ProductOrder orders" )->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )
												->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )
												->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )
												->field ( "orders.*,province.name as provinceName, city.name as cityName, area.name as areaName" )
												->where ( $condition )->order("id desc")->select ();
		$this->bindOrderDetail ( $orderLists );
		$this->assign("types", \My\Model\ProductOrderModel::$TYPES);
		$this->assign ( "orderLists", $orderLists );
		$this->display ( "{$this->modelControllerName}/orderList" );
	}
	
	// 订单详细
	public function showOrderAction() {
		$id = I ( "id", 0, "intval" );
		$order = $this->getOrder ( $id );
		$this->assign ( "order", $order );
		$this->display ( "{$this->modelControllerName}/showOrder" );
	}
	
	// 结算
	public function confirmOrderAction() {
		$order = array ();
		$d = D ( "My/ProductGoods", "Model" );
		$items = $this->getItems (); // 获得要结算的商品
		$totalPrice = 0; // 总价
		$totalShpping = $d->getShippingWay (); // 运费总价
		foreach ( $items ["items"] as &$v ) {
			$count = 0; // 购买数量
			$subtotal = 0; // 小计
			/* 处理显示属性可看 */
			foreach ( $v ['items'] as &$v0 ) {
				$tmpAttrs = array ();
				$attrInfo = $d->getAttributesInfo ( $v0 ['attrs'],  $v['productId']); // 属性信息
				foreach ( $attrInfo as $k1 => $v1 ) {
					$tmpAttrs [$v1 ['name']] = array_pop ( $v1 ['values'] );
				}
				$v0 ['attrs'] = $tmpAttrs;
				$count += $v0 ['quantity'];
				$subtotal += $v0 ['productPrice'] * $v0 ['quantity'];
			}
			$totalPrice += $subtotal;
			/* 计算运费 */
			$shipping = $d->getShipping ( $v ['productId'], $count );
			foreach ( $totalShpping as $k2 => $v2 ) { // 计算总运费
				$totalShpping [$k2] ['price'] += $shipping [$k2] ['price'];
			}
		}
	
		$defaultShipping = '2';
	
		// 运费下拉框
		$shippingOptions = array ();
		foreach ( $totalShpping as $k2 => $v2 ) {
			$shippingOptions [$k2] = "{$v2['name']} " . number_format ( $v2 ['price'], 2 ) . "元";
		}
	
		// 支付方式下拉框(在确认订单页显示支付方式,直接转入支付接口)
		$produtPayApiLists = $this->getPayApiList();
		$produtPayApiLists = array_merge($produtPayApiLists, array('COD' =>"货到付款"));
		$order = array (
				'atOnce' => $items ["atOnce"],
				'createTime' => time (),
				'orderNo' => date ( "ymdHis" ) . str_pad ( $this->sid, 6, 0, STR_PAD_LEFT ) . rand ( 1000, 9999 ), // 订单号
				'totalPrice' => $totalPrice + $totalShpping [$defaultShipping] ['price'],
				'goodsTotalPrice' => $totalPrice,
				'shippingTotalPrice' => $totalShpping, // 配送方式数据(确认订单,更改地址时使用)
				'shippingOptions' => $this->getOption ( $shippingOptions, $defaultShipping ),
				'productPayApiOptions' => $this->getOption( $produtPayApiLists ),
				'orderItems' => $items ["items"]
		);
	
		/* 获得用户默认收货地址 */
		$address = M ( "DeliverAddress address" )->join ( "__CN_PROVINCE__ province on address.province = province.code", "LEFT" )->join ( "__CN_CITY__ city on address.city = city.code", "LEFT" )->join ( "__CN_AREA__ area on address.area = area.code", "LEFT" )->field ( "address.*,province.name as provinceName, city.name as cityName, area.name as areaName" )->where ( "uid=%d", $this->uid )->order ( "status desc" )->find ();
		$address and M ( "DeliverAddress" )->where ( "id=%d", $address ['id'] )->setField ( 'status', 1 );
		$order ['address'] = $address;
		session ( "order", $order );
		$this->assign ( "buyUrl", urlencode($this->getCurrentUrl ()) );
		$this->assign ( "orderJSON", json_encode ( $order ) );
		$this->assign ( 'order', $order );
		$this->display ( "{$this->modelControllerName}/" . ACTION_NAME );
	}
	
	// 确认提交订单
	public function confirmOrderPostAction() {
		$addressId = I ( "address_id", 0 ); // 地址id
		$shippingWay = I ( "shipping_way", 0 ); // 配送方式
		$orderNo = I ( 'orderNo', 0 ); // 订单编号
		$order = session ( "order" );
		$payApitype = I("apitype", "");
		$addressLists = $order ['addressLists'];
	
		
		if ( !$order || $order ['orderNo'] !== $orderNo ) {
			$orderSaved = M("ProductOrder")->where(array( 'order_id'=>$orderNo, 'cid'=>$this->cid) )->find();
			if ( $orderSaved ) { // 订单已存在时
				$this->error ( "订单($orderNo)已超时,正在转向订单详细重新结算.",  U('ShopOrder/showOrder', "id={$orderSaved['id']}&sid={$this->cid}"));
			} elseif ( !$order || $order and (time () - $order ["createTime"]) > 3 * 60 ) { // 下单超时
				$this->error ( "订单($orderNo){$order ['orderNo']}已超时,正在转向购物车重新结算.",  $this->getCartUrl());
			}
		}
	
		/* 获得收货地址 */
		$deliverAddress = M ( "DeliverAddress" )->where ( "uid=%d and status=1", $this->uid )->find ();
		$deliverAddress or $this->error ( "没有找到默认的收货地址" );
	
		/* 配送方式 */
		$shippingWay or $order ['shippingTotalPrice'] [$shippingWay] or $this->error ( "未选择配送方式" );
		$shippingInfo = $order ['shippingTotalPrice'] [$shippingWay]; // 配送信息
	
		/* 保存订单 */
		$orderData = array (
				'order_id' => $orderNo,
				'cid' => $this->sid,
				'uid' => $this->uid,
				'shipping_fee' => $shippingInfo ['price'],
				'goods_amount' => $order ['goodsTotalPrice'],
				'order_status' => ProductOrderModel::ORDER_STATUS_PAY,
				'consignee' => $deliverAddress ['name'],
				'province' => $deliverAddress ['province'],
				'city' => $deliverAddress ['city'],
				'area' => $deliverAddress ['area'],
				'address' => $deliverAddress ['address'],
				'zipcode' => $deliverAddress ['zipcode'],
				'tel' => $deliverAddress ['tel'],
				'shipping_id' => $shippingWay,
				'shipping_name' => $shippingInfo ['name'],
				'express_name' => '',
				'create_time' => $order ['createTime'],
				'confirm_time' => 0,
				'shipping_time' => 0 );
		method_exists($this, "getOrderDataAdditionalFields") and $this->getOrderDataAdditionalFields( $orderData );
		$d = D ( "ProductOrder" );
		if ( $orderId = $d->add ( $orderData ) ) {
			// 添加所有订单商品
			$m = M ( "ProductOrderGoods" );
			$goodsList = $this->getOrderGoods( $order['orderItems'], $orderId);
			if ( false != $m->addAll ( $goodsList ) ) {
				$order ['atOnce'] or $this->cart->clearAll ();
				session ( "order", null );
				sleep(5);
				/*支付转入*/
				if ( empty($payApitype) ) {
					$order = $this->getOrder ( $orderId );
					$this->assign ( "order", $order );
					$this->display ( "{$this->modelControllerName}/showOrder" );
				} else {
					redirect($this->getPayUrl(array(
						'id' => $orderId,
						'sid' => $this->cid,
						'apitype' => $payApitype,
					)));
				}
				exit ();
			} else {
				$d->where ( "id=%d", $orderId )->setField ( "order_status", ProductOrderModel::ORDER_STATUS_INVALID );
			}
		}
		$this->error ( '订单保存错误.' );
	}
	
	
	// 取消订单
	public function cancelOrderAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "ProductOrder" );
		$d->where ( array (
				"uid" => $this->uid,
				"id" => $orderId
		) )->setField ( "order_status", ProductOrderModel::ORDER_STATUS_CANCELED ) and $this->ajaxSuccess ( "取消成功" );
		$this->ajaxError ( "取消失败" );
	}
	
	// 确认收货
	public function signInAction() {
		$orderId = I ( "id", 0, "int" );
		$d = M ( "ProductOrder" );
		$order = $d->find( $orderId );
		if($order['order_status'] == ProductOrderModel::ORDER_STATUS_SIGN) {
			// 更新订单状态
			if( false !== $d->where ( array ( "uid" => $this->uid, "id" => $orderId, ) )
			->save ( array("order_status" => ProductOrderModel::ORDER_STATUS_COMPLETED,
					"take_time" => time(),
					"deal_time" => time(),) ) ) {
					$this->afterOrderCompleted( $orderId );
					$this->ajaxSuccess ( "交易成功" );
			}
		} else {
			$this->ajaxError ( "非已发货状态，不能完成收货操作。" );
		}
		$this->ajaxError ( "提交失败，请重新确认收货" );
	}
	
	
	// 交易成功后执行
	protected function afterOrderCompleted( $orderId ) { 
		// 执行分成
		$r = M()->execute("update ".C('DB_PREFIX')."product_order_goods set partner_got = ( product_price*product_number ) * ( SUBSTRING_INDEX ( percent, ':', 1 ) / 10),
								customer_got = ( product_price*product_number ) * ( SUBSTRING_INDEX ( SUBSTRING_INDEX( percent,  ':', -2 ), ':', 1) / 10 ),
 								seller_got = ( product_price*product_number ) * ( SUBSTRING_INDEX ( percent, ':', -1 ) / 10) where order_id={$orderId}");
	}
	
	// 获得订单商品
	protected function getOrderGoods( $orderItems, $orderId ) {
		$percent = $this->config['percent']; // 默认分成
		$goodsList = array();
		foreach ( $orderItems as $v ) {
			/*获得商品单独设置的分成设置*/
			$productGoodsConfig = M("ProductGoodsConfig")->find( $v['productId'] );
			$productGoodsConfig['sharing_method'] and $percent = $productGoodsConfig['percent'];
			/*订单商品*/
			foreach ( $v ["items"] as $v0 ) {
				$orderGoodsItem = array (
						'owner_cid' => $v['ownerCid'],
						'order_id' => $orderId,
						'product_id' => $v ['productId'],
						'product_name' => $v ['name'],
						'product_pic' => $v0 ['pic'],
						'product_number' => $v0 ['quantity'],
						'product_price' => $v0 ['productPrice'],
						'product_attr' => arrayToString ( $v0 ['attrs'] ),
				);
				/*保存分成比例*/
				if ( !empty( $percent ) ) {
					$orderGoodsItem['percent'] = $percent;
				}
				$goodsList[] = $orderGoodsItem;
			}
		}
		return $goodsList;
	}
	
	
	// 获得要结算的商品
	private function getItems() {
		$items = array (
				"atOnce" => 0, // 是否立即购买
				"items" => array ()
		);
		$productId = I ( "id", 0, "intval" ); // 商品id(立即购买时)
		if (! $productId) { // 处理从购物车中选择的商品
			$productIds = I ( "Ids", 0 ); // 商品id(从购物车选择商品时)
			$items ["items"] = $this->cart->getItems (); // 暂时购买所有商品
		} else { // 处理立即购买的商品
			$id = I ( "id", 0, "intval" );
			$quantity = I ( "quantity", 1, "intval" ) and $quantity === 0 and $quantity = 1;
			$attrs = I ( "attrs", null );
			$d = D ( "My/ProductGoods", "Model" );
			// 处理立即购买属性参数,如果提交类型为数组则转为字符串类型(购买链接会再次使用)
			$product = $d->getUserSubmitGoods ( $id, $attrs ) or $this->ajaxError ( $d->getError () );
			// 转化为CartItem(参考购物车结构)
			$businessId = $this->cart->getBusinessId ( $product ['id'] );
			$items ["atOnce"] = 1;
			$items ["items"] [] = array (
					'ownerCid' => $product['ownerCid'],
					'productId' => $product ['id'],
					'name' => $product ['name'],
					'items' => array (
							$businessId => array (
									'businessId' => $businessId,
									'productPrice' => $product ['productPrice'],
									'quantity' => $quantity,
									'attrs' => $product ['selectedAttributes'],
									'pic' => $product ['pic']
							)
					)
			);
		}
		return $items;
	}
	
	/**
	 * 绑定订单详细
	 * @param unknown $orderLists 查询出的订单列表
	 */
	protected function bindOrderDetail(&$orderLists) {
		D( "My/ProductOrder" )->bindOrderDetail($orderLists);
	}
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
	 */
	protected function getOrder($id) {
		return D( "My/ProductOrder" )->getOrder($id);
	}
	
	// 获得要保存的订单数据
	protected function getOrderDataAdditionalFields( &$orderData ) {
		$orderData['pid'] = $this->pid; // 订单所属合作商
		return $orderData;
	}
	
	// 获得支付链接
	protected function getPayUrl( $params ) {
		$oldModel = C("URL_MODEL");
		$url = U("ShopPay/toPay", $params);
		C("URL_MODEL", $oldModel);
		return $url;
	}
	
	// 购物车页
	protected function getCartUrl() {
		return url ( null, 'ShopCart', 'showCart', "sid={$this->sid}" );
	}
	
	// 支付方式列表
	protected function getPayApiList() {
		$m = M("ProductPayApi");
		$produtPayApiLists = $m->where("pid=%d and status=1", $this->pid)->getField("tag,name") or $produtPayApiLists = array(); // 获得商家设置的支付接口
		return $produtPayApiLists;
	}
	
	// 获得购物车
	protected function getCart() {
		return \Utuo\PartnerCart::getCart($this->pid, $this->cid);
	}
}

?>